package com.onion.utils.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

public class UrlHelper {

    private static String DEFAULT_ENCODING = "UTF-8";

    /**
     * URL编码
     * @param srcValue
     * @return
     */
    public static String encode(String srcValue){
        try {
            return URLEncoder.encode(srcValue, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * URL解码
     * @param encodeValue
     * @return
     */
    public static String decode(String encodeValue){
        try {
            return URLDecoder.decode(encodeValue, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取URL地址中最后一段地址
     * @param url
     * @return
     */
    public static String getLastSectionByPath(String url){
        String[] section = url.split("\\?");
        int pos = section[0].lastIndexOf("/");
        if(pos != -1){
            return section[0].substring(pos+1);
        }else{
            return null;
        }
    }

    /**
     * 获取URL参数
     * @param url
     * @return
     */
    public static JSONObject getUrlParams(String url){
        String[] section = url.split("\\?");
        if(section.length == 1){
            return null;
        }else if(section.length == 2){
            JSONObject jsonParam = new JSONObject();
            String[] keyPairs = section[1].split("&");
            for(String curKeyPair : keyPairs){
                String[] item = curKeyPair.split("=");
                if(item.length == 2){
                    jsonParam.put(item[0], item[1]);
                }
            }
            return jsonParam;
        }else {
            throw new RuntimeException("Invalid URL:" + url);
        }
    }

    public static String buildUrlParam(Map<String, String> paramMap) {
        return buildUrlParam(paramMap, DEFAULT_ENCODING);
    }

    public static String buildUrlParam(Map<String, String> paramMap, String charset) {
        StringBuilder strbUrlParams = new StringBuilder();
        boolean isFirst = true;
        charset = StringUtils.isNotBlank(charset) ? charset : DEFAULT_ENCODING;
        for (String key : paramMap.keySet()) {
            if (StringUtils.isBlank(key)) {
                continue;
            }
            if (isFirst) {
                isFirst = false;
            } else {
                strbUrlParams.append("&");
            }

            String value = paramMap.get(key);
            try {
                strbUrlParams.append(URLEncoder.encode(key, charset)).append("=");
                if (StringUtils.isNotBlank(value)) {
                    strbUrlParams.append(URLEncoder.encode(value, charset));
                }
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(String.format("装配URL参数出错:key=%s,value=%s", key, value), e);
            }
        }
        return strbUrlParams.toString();
    }

    public static String buildUrl(String url, Map<String,String> paramMap){
        return buildUrl(url, paramMap, DEFAULT_ENCODING);
    }

    public static String buildUrl(String url, Map<String,String> paramMap, String charset){
        if(StringUtils.isBlank(url)){
            throw new RuntimeException("[buildUrl]装配URL出错: url为空");
        }
        String urlParam = buildUrlParam(paramMap, charset);
        if (url.indexOf("?") != -1) {
            if ( url.endsWith("?") ) {
                return String.format("%s%s", url, urlParam);
            }else{
                return String.format("%s&%s", url, urlParam);
            }
        }else{
            return String.format("%s?%s", url, urlParam);
        }
    }

}